<style lang="less">
    @import "../../styles/common.less";
    @import 'staff.less';
</style>

<template>
    <div class="margin-top-10">
        <Row type="flex" justify="space-between">
            <Row>
                <Button type="primary" @click="showModal">
                    添加访客
                </Button>
                <Dropdown @on-click="handleBatchUpload">
                    <Button type="primary">
                        批量操作
                        <Icon type="arrow-down-b"></Icon>
                    </Button>
                    <DropdownMenu slot="list">
                        <DropdownItem name="guest">批量上传访客</DropdownItem>
                        <DropdownItem name="feature">批量注册特征</DropdownItem>
                        <DropdownItem name="avatar">批量注册头像</DropdownItem>
                    </DropdownMenu>
                </Dropdown>
                <a href="#" type="primary" style="{color:#000;text-decoration:underline;margin-left: 5px;}"
                   @click="downloadModal = true">查看批量结果</a>
            </Row>
            <Row>
                <Input v-model="queryWord" @on-enter="searchGuest" placeholder="请输入姓名..."
                       style="width: 150px;margin-right:3px"></Input>
                <Button @click="searchGuest" type="primary">查询</Button>
            </Row>
        </Row>
        <div class="margin-top-10">
            <Table :columns="guestColumn" :data="guestData" :loading="tableLoading"></Table>
        </div>
        <Row type="flex" justify="end" class="margin-top-10">
            <Page :total="totalGuest" :current="currentPage" :page-size="pageSize" @on-change="getGuest" show-total>
                显示第{{currentIndex + 1}}-{{currentIndex + pageSize}}条，总数为{{totalGuest}}条
            </Page>
        </Row>

        <Modal v-model="addGuestModal.guest_2" v-bind:title="guestModalTitle.guest_2" :scrollable="true"
               class-name="vertical-center-modal" :mask-closable="false"
               @on-cancel="resetForm('guestInfoForm_2','guest_2_avatar','guest_2')">
            <Form ref="guestInfoForm_2" :model="guestInfo.guest_2" :label-width="55"
                  :rules="ruleValidate.guest_2">
                <!--照片-->
                <Row type="flex" justify="center" style="margin-bottom: 5px">
                    <div style="margin-bottom: 10px">
                        <a href="javascript:;" class="staff-file" ref="guest_2_avatar">
                            <input type="file" accept="image/png, image/jpeg, image/jpg"
                                   @change='preview_guest_2' title=" ">
                        </a>
                    </div>
                </Row>
                <Row type="flex" justify="space-between">
                    <Col style="width: 48.5%">
                    <FormItem label="日期" aria-colspan="20" prop="validate_date">
                        <DatePicker v-model="guestInfo.guest_2.validate_date" type="daterange"
                                    placeholder="默认所有时间" format="yyyy/MM/dd"
                                    style="width: 100%" @on-change="handleDateChange('guestInfoForm_2')"></DatePicker>
                    </FormItem>
                    <FormItem label="电话" prop="user_phone">
                        <Input v-model.trim="guestInfo.guest_2.user_phone" placeholder="请输入电话号码"/>
                    </FormItem>
                    <FormItem label="接待" prop="user_receptionist">
                        <Input v-model.trim="guestInfo.guest_2.user_receptionist" placeholder="请输入接待人姓名"/>
                    </FormItem>
                    </Col>
                    <Col style="width: 48.5%">
                    <FormItem label="姓名" prop="user_name">
                        <Input v-model.trim="guestInfo.guest_2.user_name" placeholder="请输入姓名"/>
                    </FormItem>
                    <FormItem label="性别" prop="user_sex">
                        <RadioGroup v-model="guestInfo.guest_2.user_sex">
                            <Radio label="1">男</Radio>
                            <Radio label="0">女</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="单位" prop="user_company">
                        <Input v-model.trim="guestInfo.guest_2.user_company" placeholder="请输入单位名称"/>
                    </FormItem>
                    </Col>
                </Row>
                <Row>
                    <FormItem label="主标题" prop="user_mark" >
                        <Input v-model="guestInfo.guest_2.user_mark" placeholder="请输入标语"/>
                    </FormItem>
                </Row>
                <Row>
                    <FormItem label="副标题" prop="user_mark2" style="margin-bottom: 2px">
                        <Input v-model="guestInfo.guest_2.user_mark2" placeholder="请输入副标语"/>
                    </FormItem>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="primary" @click="handleSubmit('guestInfoForm_2','guest_2')">提交</Button>
            </div>
        </modal>
        <Modal width="532" style="{margin-top: 10px}"
               :mask-closable="false"
               :closable="false"
               v-model="modAvatar" >
            <spin v-show="featureLoading" size="large" fix></spin>
            <a class="ivu-modal-close" @click="modAvatar = false">
                <Icon type="ios-close-empty"></Icon>
            </a>
            <div  slot="header" class="ivu-modal-header-inner">
                修改【{{modAvatarInfo.user_name}}】的人脸特征
            </div>
            <Row v-if="modUpload">
                <uploader :count="uploadedAvatarRegsLength" :maxlength="FEATURE_MAX"
                          @fileChange="handleUserAvatarRegUpload" @fileAdd="handleUserAvatarRegAdd">
                    <!-- Uploader的标题slot -->
                    <span slot="title">上传特征</span>
                    <!-- 需要预览时，增加UploaderFiles容器 -->
                    <uploaderfiles slot="uploader-files">
                        <uploaderfile v-for="(imgSrc,i) in uploadedAvatarRegs" :key="i"
                                      :image-url="createSnapshot(imgSrc)" @click="handleUserAvatarRegRemove(imgSrc)">
                        </uploaderfile>
                    </uploaderfiles>
                </uploader>
            </Row>
            <Row type="flex" justify="start" v-else>
                <img v-for="(imgSrc,i) in modAvatarInfo.avatarReg" :key="i"
                     style="width:80px;height:80px;margin:10px;object-fit: cover;cursor: pointer"
                     :src="imgSrc"
                     @click="handleShowUserAvatarReg(i,modAvatarInfo.avatarReg.length,imgSrc)">
            </Row>
            <div slot="footer" v-if="modUpload">
                <Button type="primary" size="large" @click="uploadUserAvatarReg(modAvatarInfo.user_id)">确认上传</Button>
            </div>
            <div slot="footer" v-else>
                <Button type="error" size="large"
                        @click="handleDelAllFeature(modAvatarInfo.user_id, modAvatarInfo.user_name)">全部删除
                </Button>
                <Button type="primary" size="large" @click="modUpload=true">重新上传</Button>
            </div>
        </Modal>
        <Modal v-model="featureModal"
               class="staff-imgShow"
               :closable="false"
               style="{margin-top: 10px}">
            <a class="ivu-modal-close" @click="featureModal = false">
                <Icon type="ios-close-empty"></Icon>
            </a>
            <div slot="header" class="ivu-modal-header-inner">
                {{featureModalTitle}}
            </div>
            <div class="ivu-carousel">
                <Button class="left ivu-carousel-arrow ivu-carousel-arrow-hover"
                        @click="handleImgLeft"
                        v-show="previewImgLeftVisible">
                    <Icon type="chevron-left"></Icon>
                </Button>
                <Row type="flex" justify="center">
                    <div :style="{backgroundImage:imgSrc}" style="height: 100%;width: 100%;background-size: auto 100%;background-repeat: no-repeat;background-position: center top;" >
                        <div style="padding: 60%"></div>
                    </div>
                </Row>
                <Button class="right ivu-carousel-arrow ivu-carousel-arrow-hover"
                        @click="handleImgRight"
                        v-show="previewImgRightVisible">
                    <Icon type="chevron-right"></Icon>
                </Button>
            </div>
        </Modal>
        <Modal v-model="uploadModal" @on-cancel="hideUploadModal">
            <div slot="header">
                <p>导入表格<span style="font-weight: 100;font-size: 12px;margin-left: 5px">(请严格按照<a :href="excelFile" download="模板.xlsx">模板</a>格式上传表格)</span></p>
            </div>
            <HorizonUploader ref="uploader"></HorizonUploader>
            <div slot="footer">
                <Button type="primary" @click="handleUpload">上传</Button>
            </div>
        </Modal>
        <DownloadTableModal v-model="downloadModal"></DownloadTableModal>
        <UploadFeatureModal v-model="uploadFeatureModal" user_type="stranger" file_type="feature">
            <div slot="notice">
                注意事项
                <ol>
                    <li>1.只支持ZIP格式压缩包</li>
                    <li>2.请等待上传完成后再刷新页面</li>
                    <li>3.上传结果请稍候查看</li>
                    <li>4.1000组照片估计用时25分钟</li>
                </ol>
            </div>
        </UploadFeatureModal>
        <UploadFeatureModal v-model="uploadAvatarModal" user_type="stranger" file_type="avatar">
        </UploadFeatureModal>
    </div>
</template>

<script>
    import {
        addOrUpdateGuest,
        getGuestData,
        deleteUser,
        getAvatar,
        getFeature,
        regFeature,
        delFeature,
        uploadGuestData,
        recovery,
    } from "../../controllers/user";

    import Uploader from "../../views/weiget/uploader.vue";
    import Uploaderfile from "../../views/weiget/uploader-file.vue";
    import Uploaderfiles from "../../views/weiget/uploader-files.vue";
    import HorizonUploader from "./components/HorizonUploader.vue"
    import UploadFeatureModal from './UploadFeatureModal.vue'
    import DownloadTableModal from "./DownloadTableModal.vue"

    import Constant from "../../libs/constants";
    import _ from "lodash";
    import pic from "../../images/upload.png";
    import fakeAvatar from "../../images/default_avatar.png";
    import DateUtils from "../../../node_modules/iview/src/utils/date";
    import row from "../../../node_modules/iview/src/components/grid/row";
    import col from "../../../node_modules/iview/src/components/grid/col"
    import ImageUtils from "@/libs/image.js";

    import iconDelete from "../../images/delete.png"
    import iconEdit from "../../images/edit.png"
    import iconFeature from "../../images/feature.png"

    import excelFile from "../../assets/guestExcel.xlsx"

    import Tooltip from "../../../node_modules/iview/src/components/tooltip/tooltip"
    import Btn from "../../../node_modules/iview/src/components/button/button"

    export default {
        components: {
            Uploader,
            Uploaderfile,
            Uploaderfiles,
            HorizonUploader,
            UploadFeatureModal,
            DownloadTableModal,
            Tooltip,
            Btn
        },
        data() {
            const validateDate = (rule, value, callback) => {
                if (!value || value.length != 2 ) {
                    callback(new Error('日期格式错误'));
                }else {
                    callback()
                }
            };
            return {
                FEATURE_MIN: Constant.FEATURE_MIN,
                FEATURE_MAX: Constant.FEATURE_MAX,
                IMG_WIDTH_MIN:Constant.IMG_WIDTH_MIN,
                IMG_WIDTH_MAX:Constant.IMG_WIDTH_MAX,
                IMG_HEIGHT_MIN:Constant.IMG_HEIGHT_MIN,
                IMG_HEIGHT_MAX:Constant.IMG_HEIGHT_MAX,
                addGuest: false,
                addGuestModal: {
                    guest_2: false,
                },
                edit_flag: false,
                user_id: '',
                guestModalTitle: {
                    guest_2: "添加 临时访客",
                },
                addGuestModalTitle: {
                    guest_2: "添加 临时访客",
                },
                editGuestModalTitle: {
                    guest_2: "编辑 临时访客资料",
                },
                guestInfo: {
                    guest_2: {
                        user_type: '2',
                        user_name: "",
                        user_phone: "",
                        user_avatar: "",
                        user_mark: "",
                        user_mark2: "",
                        user_sex: "0",
                        validate_date: "",
                        access_from: "",
                        access_to: "",
                        user_receptionist:"",
                        user_company:"",
                    },
                },
                ruleValidate: {
                    "guest_2": {
                        user_name: [{required: true, message: "姓名不可以为空", trigger: "change"}],
//                        user_mark: [{required: true, message: "备注不可以为空", trigger: "change"}],
//                        user_sex: [{required: true, message: "性别不可以为空", trigger: "change"}],
//                        validate_date: [{required:false, validator: validateDate, trigger: 'change' }],
                        user_phone: [
                            {
                                pattern: /^1\d{10}$/,
                                message: "电话格式不正确",
                                trigger: "blur"
                            }
                        ],
                    },
                },
                guestData: [],
                totalGuest: 0,
                currentPage: 1,
                excelFile:excelFile,
                pageSize: Constant.PAGE_SIZE,
                tableLoading: true,
                queryWord: "",
                guestColumn: [
                    {
                        title: "姓名",
                        key: "user_name",
                        align: "center",
                        width: '10%'
                    },
                    {
                        title: "头像",
                        key: "user_avatar",
                        align: "center",
                        width: '10%',
                        render: (h, {row, column, index}) => {
                            //拼装url
                            let imgSrc = fakeAvatar;
                            let encode = row[column.key];
                            if (encode) {
                                imgSrc =  encode;
                            }
                            return (<div><img class="user-avatar" alt="头像" src={imgSrc}/></div>);
                        }
                    },
                    {
                        title: "用户类型",
                        key:"user_type_disp",
                        align: "center",
                        width: '100',
                    },
                    // {
                    //     title: "备注",
                    //     align: "center",
                    //     width: "10%",
                    //     render: (h, {row, column, index}) => {
                    //         let company = row.user_company
                    //         let receptionist = row.user_receptionist
                    //         if (row.user_type == "2") {
                    //             return row.user_mark
                    //         } else {
                    //             return (
                    //                 <div >
                    //                     <row type="flex" justify="center">
                    //                         <col>
                    //                             <div align="right" style={{minWidth:'50px',lineHeight:'25px'}}><b>单位:</b>&nbsp;</div>
                    //                             <div align="right" style={{minWidth:'50px',lineHeight:'25px'}}><b>接待人:</b>&nbsp;</div>
                    //                         </col>
                    //                         <col>
                    //                             <div align="left" style={{minWidth:'50px',lineHeight:'25px'}}>{company}</div>
                    //                             <div align="left" style={{minWidth:'50px',lineHeight:'25px'}}>{receptionist}</div>
                    //                         </col>
                    //                     </row>
                    //                 </div>
                    //             );
                    //         }
                    //     }
                    // },
                    {
                        title: "有效日期",
                        ellipsis: true,
                        align: "center",
                        width: '110',
                        render: (h, {row, column, index}) => {
                            let access_from = row.access_from || ''
                            let access_to = row.access_to || ''
                            if(access_from == '' || access_to == ''){
                                return ''
                            }
                            let form = DateUtils.format(DateUtils.parse(access_from,"yyyyMMdd"),"yyyy年MM月dd日")
                            let to = DateUtils.format(DateUtils.parse(access_to,"yyyyMMdd"),"yyyy年MM月dd日")
                            return (
                                <row>
                                    <div style={{lineHeight:'25px'}}>{form}</div>
                                    <div style={{lineHeight:'25px'}}>{to}</div>
                                </row>
                        )
                            ;
                        }
                    },
                    {
                        title: "特征",
                        key: "user_picReg",
                        align: "center",
                        render: (h, {row, column, index}) => {
                            let encodes = row[column.key];
                            return (<div>
                                {_.map(encodes, encode => {
                                    //拼装url
                                    let imgSrc = fakeAvatar;
                                    if (encode !== "") {
                                        imgSrc = "data:image/jpg;base64," + encode;
                                    }
                                    return (<img class="user-avatar" alt="特征" src={imgSrc}/>);
                                })}
                                </div>);
                        }
                    },
                    {
                        title: "操作",
                        width: '180',
                        align: "center",
                        render: (h, {row, column, index}) => {
                            const user_id = row.user_id;
                            const user_name = row.user_name;
                            const user_type = "guest_" + row.user_type;
                            return (
                                <div class="operation">
                                    <Tooltip content="特征修改" placement="bottom">
                                        <Btn style={{background: `url( ${iconFeature})`}} onClick={()=>this.handleEditFeature(user_id, user_name)}/>
                                    </Tooltip>
                                    <Tooltip content="编辑" placement="bottom">
                                        <Btn style={{background: `url( ${iconEdit})`}} onClick={()=>this.editGuest(user_type, user_id,index)}/>
                                    </Tooltip>
                                    <Tooltip content="删除" placement="bottom">
                                        <Btn style={{background: `url( ${iconDelete})`}} onClick={()=>this.removeGuest(user_id, user_name)}/>
                                    </Tooltip>
                                </div>
                            )
                        }
                    }
                ],
                modAvatar: false,
                modUpload: false,
                modAvatarInfo: {
                    user_id: "",
                    user_name: "",
                    avatarReg: []
                },
                previewImgInfo:{
                    currentIndex:0,
                    total:0
                },
                uploadedAvatarRegs: [],
                featureModal:false,
                imgSrc:"",
                featureLoading:true,
                uploadModal:false,
                uploadFeatureModal:false,
                downloadModal:false,
                uploadAvatarModal:false
            };
        },
        computed: {
            currentIndex: function () {
                return (this.currentPage - 1) * this.pageSize;
            },
            uploadedAvatarRegsLength: function () {
                return this.uploadedAvatarRegs.length;
            },
            featureModalTitle:function () {
                let i = this.previewImgInfo.currentIndex+1
                let cnt = this.previewImgInfo.total
                return i + "/" + cnt
            },
            previewImgLeftVisible:function () {
                return this.previewImgInfo.currentIndex > 0
            },
            previewImgRightVisible:function () {
                return this.previewImgInfo.currentIndex < this.previewImgInfo.total - 1
            }
        },
        mounted(){
            document.addEventListener("keydown", this.handleKeyDown);
        },
        beforeDestroy () {
            document.removeEventListener('keydown', this.handleKeyDown);
        },
        created() {
            this.loadGuestData()
        },
        methods: {
            showModal() {
                let type = 'guest_2';
                this.addGuestModal[type] = true;
                this.user_id = '';
            },
            searchGuest() {
                // 检验关键词
                this.currentPage = 1;
                this.tableLoading = true;
                this.loadGuestData()
            },
            loadGuestData(){
                getGuestData(this.currentPage, this.pageSize, this.queryWord)
                    .then(json => {
                        let {total, data} = transGuestData(json);
                        this.totalGuest = total;
                        this.guestData = data;
                        this.tableLoading = false;
                        return _.map(data,item=>item.user_id);
                    })
                    .then(user_ids => this.asyncAvatar(user_ids));
            },
            handleSubmit(form, data) {
                this.$refs[form].validate(valid => {
                    if (valid) {
                        this.translateDate(data)
                        addOrUpdateGuest(this.edit_flag ? "update" : "register", this.guestInfo[data]).then(res => {
                            this.$Message.info("更新成功")
                            this.addGuestModal[data] = false
                            this.getGuest(this.currentPage);
                            this.resetForm(form, data + '_avatar', data)
                        })
                    } else {
                        this.$Message.info("请检查表单")
                    }
                });
            },
            translateDate(data) {
                let access_from = this.guestInfo[data].validate_date[0];
                let access_to = this.guestInfo[data].validate_date[1];
                if (access_from)
                    this.guestInfo[data].access_from = DateUtils.format(access_from, "yyyyMMdd")
                if (access_to)
                    this.guestInfo[data].access_to = DateUtils.format(access_to, "yyyyMMdd")
            },
            preview_guest_2(e){
                this.preview(e,"guest_2_avatar","guest_2")
            },
            preview(e, id, modal) {
                let file = e.target.files[0];
                ImageUtils.compress(file, {
                    compress: {
                        width: 480,
                        height: 480,
                        quality: 0.8,
                    },
                    type: 'file'
                }, (res,w,h) => {
                    if (res) {
                        let reader = new FileReader();
                        reader.onload = () => {
                            this.$refs[id].style.backgroundImage = "url('" + reader.result + "')";
                            this.guestInfo[modal].user_avatar = reader.result.split(",")[1];
                            reader.onload = null;
                        };
                        reader.readAsDataURL(res);

                        // // 更新头像
                        // if (this.edit_flag) {
                        //     let data = new FormData();
                        //     data.append('avatar', res);
                        //     data.append('user_id', this.user_id);
                        //     updateAvatar(data).then(res => {
                        //         this.$Message.success("头像更新成功!");
                        //     })
                        // }
                    }else{
                        this.$Message.error("图片过大，请更换")
                    }

                })

            },
            resetForm(form, picId, data) {
                setTimeout(() => {
                    this.$refs[form].resetFields();
                    this.$refs[picId].style.backgroundImage = "url(" + pic + ")";
                    this.guestInfo[data].user_avatar = ""
                    this.setModalTitle(false)
                }, 500)

            },
            getGuest(page) {
                //获取分页参数，请求后端数据
                //console.log(page);
                //检验页码上下限
                this.currentPage = page;
                this.tableLoading = true;
                this.loadGuestData()
            },
            asyncAvatar(user_ids) {
                _.forEach(user_ids, (user_id,index) => {
                    getAvatar(user_id).then(json => {
                        if (this.guestData[index] === undefined) {
                            console.log("存在数据加载错误，可能在异步过程完成前修改了原始的表数据");
                        }
                        let result = transAvatar(json);
//                        this.guestData[index].user_avatar = result.user_avatar;
                        this.guestData[index].user_picReg = result.user_feature;
                    });
                    return true;
                });
            },
            handleEditFeature(user_id, user_name) {
                this.uploadedAvatarRegs.splice(0, this.uploadedAvatarRegs.length);
                // 通过id检索全部人脸特征
                this.modAvatarInfo.user_id = user_id;
                this.modAvatarInfo.user_name = user_name;
                this.modAvatarInfo.avatarReg = [];
                this.featureLoading = true;
                this.modUpload = false;
                this.modAvatar = true;
                getFeature(user_id).then(res => {
                    if (res.data && res.data.length > 0) {
                        this.modAvatarInfo.avatarReg = _.map(
                            res.data,
                            i => "data:image/jpg;base64," + i
                        );
                        this.modUpload = false;
                    } else {
                        this.modUpload = true;
                    }
                    this.featureLoading = false;
                });
            },
            handleDelAllFeature(userId, userName) {
                this.$Modal.confirm({
                    title: "确认",
                    content: "删除【" + userName + "】的特征库？",
                    onOk: () => {
                        delFeature({user_id: userId}).then(res => {
                            if (res.code === 0) {
                                this.$Message.success("删除成功!");
                                this.modAvatar = false;
                                this.getGuest(this.currentPage);
                            } else {
                                this.$Message.error("删除失败!");
                            }
                        });
                    }
                });
            },
            handleUserAvatarRegUpload(imgs) {
                _.forEach(imgs, file => {
                    if (["image/jpg", "image/jpeg", "image/png"].indexOf(file.type) < 0) {
                        return false;
                    }
                    if (this.uploadedAvatarRegsLength >= this.FEATURE_MAX) {
                        return false;
                    }

                    // base64
                    const reader = new FileReader();
                    let _this = this;
                    let name = file.name
                    reader.onload = function (e) {
                        let img = new Image()
                        img.onload = function(){
                            let width = img.width
                            let height = img.height
                            if(width < _this.IMG_WIDTH_MIN || width > _this.IMG_WIDTH_MAX) {
                                let errMsg = "图片" + name + "宽度存在问题，应在(" + _this.IMG_WIDTH_MIN + "-" + _this.IMG_WIDTH_MAX +")之间"
                                _this.$Message.error(errMsg)
                            }else if(height < _this.IMG_HEIGHT_MIN || height > _this.IMG_HEIGHT_MAX){
                                let errMsg = "图片" + name + "高度存在问题，应在(" + _this.IMG_HEIGHT_MIN + "-" + _this.IMG_HEIGHT_MAX +")之间"
                                _this.$Message.error(errMsg)
                            }else{
                                _this.uploadedAvatarRegs.push({
                                    picdata: e.target.result.split(',')[1],
                                    type: file.type.split("/")[1]
                                });
                            }
                        }
                        img.src = e.target.result
                    };
                    reader.readAsDataURL(file);
                    return true;
                });
            },
            handleUserAvatarRegAdd(img,width,height){
                if (["image/jpg", "image/jpeg", "image/png"].indexOf(img.type) < 0) {
                    return false;
                }
                if (this.uploadedAvatarRegsLength >= this.FEATURE_MAX) {
                    return false;
                }
                let name = img.name
                if(width < this.IMG_WIDTH_MIN || width > this.IMG_WIDTH_MAX) {
                    let errMsg = "图片" + name + "宽度存在问题，应在(" + this.IMG_WIDTH_MIN + "-" + this.IMG_WIDTH_MAX +")之间"
                    this.$Message.error(errMsg)
                    return
                }else if(height < this.IMG_HEIGHT_MIN || height > this.IMG_HEIGHT_MAX){
                    let errMsg = "图片" + name + "高度存在问题，应在(" + this.IMG_HEIGHT_MIN + "-" + this.IMG_HEIGHT_MAX +")之间"
                    this.$Message.error(errMsg)
                    return
                }
                const reader = new FileReader();
                let _this = this
                reader.onload = function (e) {
                    _this.uploadedAvatarRegs.push({
                        picdata: e.target.result.split(',')[1],
                        type: img.type.split("/")[1]
                    });
                }
                reader.readAsDataURL(img)
            },
            handleUserAvatarRegRemove(item) {
                // 从 upload 实例删除数据
                this.uploadedAvatarRegs.splice(this.uploadedAvatarRegs.indexOf(item), 1);
            },
            createSnapshot(item) {
                return "data:image/" + item.type + ";base64," + item.picdata;
            },
            uploadUserAvatarReg(userId) {
                //检查待上传文件
                //组装上传信息
                //发起请求
                //处理上传过程
                //成功上传or错误
                //清除URL.revokeObjectURL(objectURL);//注销内存使用。

                // TODO
                if (this.uploadedAvatarRegsLength < this.FEATURE_MIN) {
                    this.$Message.info("请选择特征图");
                    return;
                }

//                let pictures = [];
//                this.uploadedAvatarRegs.forEach(function (value, index, array) {
//                    pictures.push({picdata: File.transFeature(value), type: value.type.split("/")[1]});
//                });
//                console.log(JSON.stringify({_id: userId, pictures: this.pictures}))

                // 注册特征
                regFeature({user_id: userId, feature_pic: this.uploadedAvatarRegs}).then(res => {
                    if (res.code === 0) {
                        this.$Message.success('注册成功');
                        this.modAvatar = false;
                        this.getGuest(this.currentPage);
                    }
                });
            },
            editGuest(type, user_id, index) {
                let data = this.guestData[index];
                this.guestInfo[type].user_id = data.user_id;
                this.user_id = data.user_id;
                this.guestInfo[type].user_name = data.user_name;
                this.guestInfo[type].user_avatar = data.user_avatar;
                this.guestInfo[type].user_phone = data.user_phone;
                this.guestInfo[type].access_from = data.access_from;
                this.guestInfo[type].access_to = data.access_to;
                this.guestInfo[type].user_sex = data.user_sex;
                this.guestInfo[type].user_mark = data.user_mark;
                this.guestInfo[type].user_mark2 = data.user_mark2;
                this.guestInfo[type].user_company = data.user_company;
                this.guestInfo[type].user_receptionist = data.user_receptionist;
                //日期
                this.guestInfo[type].validate_date = [
                    DateUtils.parse(this.guestInfo[type].access_from, 'yyyyMMdd'),
                    DateUtils.parse(this.guestInfo[type].access_to, 'yyyyMMdd')
                ]
                //头像
                let avatar = this.guestInfo[type].user_avatar == "" ? pic : this.guestInfo[type].user_avatar
                this.$refs[type + "_avatar"].style.backgroundImage = "url(" + avatar + ")";
                // 初始显示完就置空，后面一旦赋值就是更新图片的base64
                this.guestInfo[type].user_avatar = '';

                //设置编辑状态
                this.setModalTitle(true)
                //show
                this.addGuestModal[type] = true

//                this.staffInfo.user_sex = data.user_sex;
//                this.$refs.user_sex = data.user_sex;
//                this.$refs["avatar"].style.backgroundImage =
//                    "url(data:image/jpg;base64," + this.staffInfo.user_avatar + ")";
//                this.addStaffModalTitle = "编辑信息";
//                this.addStaff = true;
            },
            setModalTitle(flag) {
                this.edit_flag = flag
                if (flag) {
                    this.guestModalTitle = this.editGuestModalTitle
                } else {
                    this.guestModalTitle = this.addGuestModalTitle
                }
            },
            removeGuest(uid, name) {
                this.$Modal.confirm({
                    title: "确认",
                    content: "移除成员【" + name + "】？",
                    onOk: () => {
                        // 删除基本信息
                        deleteUser({user_id:[uid]}).then(res => {
                            this.$Message.success("删除成功!");
                            this.getGuest(this.currentPage);
                        });
                    }
                });
            },
            handleShowUserAvatarReg(i,cnt,img){
                this.imgSrc ="url("+ img+")"
                this.previewImgInfo.currentIndex = i
                this.previewImgInfo.total = cnt
                this.featureModal=true
            },
            handleKeyDown(e){
                switch (e.keyCode){
                    case 27:
                        if(this.featureModal){
                            this.featureModal = false
                        }else if(this.modAvatar){
                            this.modAvatar = false
                        }
                        break;
                    case 37:
                        this.handleImgLeft()
                        break;
                    case 39:
                        this.handleImgRight()
                        break;
                }
            },
            handleImgLeft(){
                let index = this.previewImgInfo.currentIndex
                if(index > 0){
                    this.previewImgInfo.currentIndex--
                    this.imgSrc = "url("+this.modAvatarInfo.avatarReg[index-1]+")"
                }
            },
            handleImgRight(){
                let index = this.previewImgInfo.currentIndex
                if(index < this.modAvatarInfo.avatarReg.length-1){
                    this.previewImgInfo.currentIndex++
                    this.imgSrc = "url("+this.modAvatarInfo.avatarReg[index+1]+")"
                }
            },
            handleDateChange(form){
                console.log("date change")
            },
            hideUploadModal(){
                this.uploadModal = false
                this.$refs['uploader'].reset()
            },
            handleUpload(){
                if(!this.$refs['uploader'].hasFile){
                    this.$Message.error("请先选择文件")
                    return
                }
                var formData = new FormData()
                formData.append("user_info_xlsx",this.$refs['uploader'].file)
                uploadGuestData(formData).then(json=>{
                    if(json.code == 0){
                        this.$Message.success(json.msg)
                        this.hideUploadModal()
                        this.getGuest(this.currentPage)
                    }
                })
            },
            handleBatchUpload(type){
                switch (type){
                    case 'guest':
                        this.uploadModal = true
                        break
                    case 'feature':
                        this.uploadFeatureModal = true
                        break
                    case 'avatar':
                        this.uploadAvatarModal = true
                        break
                }
            },
        }
    };

    function transGuestData(json) {
        //检测状态码
        if (json.code !== 0) {
            //非正常就返回空表
            return {total: 0, result: {}};
        }
        let data = json.data;
        //检测数据块存在及长度
        if (data === undefined) {
            return {total: 0, result: {}};
        }
        let {total, result} = data;

        //to-do:检查data成员
        return {
            total,
            data:
                _.map(result, v => ({
                    user_id: v["user_id"],
                    user_name: v["user_name"],
                    user_type: v["user_type"],
                    user_type_disp: v["user_type_disp"],
                    user_avatar: v["user_avatar"], //to-do:缺占位图base64
                    user_picReg: [],
                    user_sex: v["user_sex"] === 0 ? "0" : "1",
                    user_phone: v["user_phone"],
                    access_from: v["access_from"] || "",
                    access_to: v["access_to"] || "",
                    user_mark: v["user_mark"] || "",
                    user_mark2: v["user_mark2"] || "",
                    user_company: v["user_company"] || "",
                    user_receptionist: v["user_receptionist"] || "",
                }))
        };
    }

    function transAvatar(json) {
        //检测状态码
        if (json.code !== 0) {
            //非正常就返回空表
            return {user_avatar: "", user_feature: ["", "", ""]};
        }
        let data = json.data;
        //检测数据块存在及长度
        if (data === undefined || data.length === 0) {
            return {user_avatar: "", user_feature: ["", "", ""]};
        }
        //提取->检验->组装
        return data[0];
    }
</script>
